<template>
  <div class="playlist-manage">
    <!-- 顶部操作栏：批量删除 + 新增歌单按钮 -->
    <div class="top-operation-bar" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
      <!-- 批量删除歌单按钮 -->
      <el-button
          type="danger"
          :icon="Delete"
          @click="handleBatchDeletePlaylists"
          :disabled="selectedPlaylistIds.length === 0 || loading"
      >
        批量删除歌单（{{ selectedPlaylistIds.length }} 个）
      </el-button>
      <!-- 新增歌单按钮 -->
      <el-button type="primary" :icon="Plus" @click="openAddDialog">
        新增歌单
      </el-button>
    </div>


    <!-- 歌单查询表单 -->
    <div class="search-section">
      <div class="search-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="歌单">
              <el-input v-model="searchForm.title" placeholder="请输入歌单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="风格">
              <el-select
                  v-model="searchForm.style"
                  placeholder="请选择风格"
                  class="style-select"
                  clearable
                  @change="handleSearch"
              >
                <el-option label="全部" value="" />
                <el-option label="朋克" value="朋克" />
                <el-option label="粤语流行" value="粤语流行" />
                <el-option label="国风" value="国风" />
                <el-option label="电子" value="电子" />
                <el-option label="非洲节拍" value="非洲节拍" />
                <el-option label="嘻哈说唱" value="嘻哈说唱" />
                <el-option label="韩国流行" value="韩国流行" />
                <el-option label="古典" value="古典" />
                <el-option label="节奏布鲁斯" value="节奏布鲁斯" />
                <el-option label="华语流行" value="华语流行" />
                <el-option label="国风流行" value="国风流行" />
                <el-option label="摇滚" value="摇滚" />
                <el-option label="轻音乐" value="轻音乐" />
                <el-option label="日本流行" value="日本流行" />
                <el-option label="原声带" value="原声带" />
                <el-option label="乡村" value="乡村" />
                <el-option label="欧美流行" value="欧美流行" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="search-item">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch" class="search-btn">搜索</el-button>
              <el-button :icon="Refresh" @click="resetSearch" class="reset-btn">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 歌单表格 -->
    <div class="content-section">
      <el-table
          :data="playlistList"
          border
          style="width: 100%"
          :loading="loading"
          @selection-change="handleSelectChange"
          @select-all="handleSelectAll"
          :row-key="(row) => row.id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="id" label="歌单编号" width="100" />
        <el-table-column prop="cover" label="封面" width="100">
          <template #default="scope">
            <el-image
                :src="scope.row.cover || '/static/default-avatar.png'"
                style="width: 60px; height: 60px; object-fit: cover; cursor: pointer;"
                preview-src-list="[scope.row.cover || '/static/default-avatar.png']"
                @click="openCoverDialog(scope.row.id, scope.row.cover)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="歌单名称" />
        <el-table-column prop="style" label="风格" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.style }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="intro" label="简介" width="300" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button type="text" :icon="Edit" @click="openEditBaseDialog(scope.row.id)">修改</el-button>
            <el-button type="text" :icon="Delete" @click="deletePlaylist(scope.row.id)" style="color: #ff4d4f;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; text-align: right;">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentPageChange"
        />
      </div>
    </div>

    <!-- 1. 新增/编辑歌单基础信息弹窗（名称/风格/简介） -->
    <el-dialog v-model="baseDialogVisible" :title="baseDialogTitle" width="600px" :close-on-click-modal="false">
      <el-form
          ref="baseFormRef"
          :model="baseForm"
          label-width="120px"
          :rules="baseFormRules"
          style="margin-top: 10px;"
      >
        <el-form-item label="歌单名称" prop="title">
          <el-input v-model="baseForm.title" placeholder="请输入歌单名称" />
        </el-form-item>
        <el-form-item label="歌单风格" prop="style">
          <el-select
              v-model="baseForm.style"
              placeholder="请选择歌单风格"
              clearable
          >
            <el-option label="朋克" value="朋克" />
            <el-option label="粤语流行" value="粤语流行" />
            <el-option label="国风" value="国风" />
            <el-option label="电子" value="电子" />
            <el-option label="非洲节拍" value="非洲节拍" />
            <el-option label="嘻哈说唱" value="嘻哈说唱" />
            <el-option label="韩国流行" value="韩国流行" />
            <el-option label="古典" value="古典" />
            <el-option label="节奏布鲁斯" value="节奏布鲁斯" />
            <el-option label="华语流行" value="华语流行" />
            <el-option label="国风流行" value="国风流行" />
            <el-option label="摇滚" value="摇滚" />
            <el-option label="轻音乐" value="轻音乐" />
            <el-option label="日本流行" value="日本流行" />
            <el-option label="原声带" value="原声带" />
            <el-option label="乡村" value="乡村" />
            <el-option label="欧美流行" value="欧美流行" />
          </el-select>
        </el-form-item>
        <el-form-item label="歌单简介" prop="intro">
          <el-input v-model="baseForm.intro" type="textarea" :rows="3" placeholder="请输入歌单简介（不超过500字）" />
        </el-form-item>

        <!-- 编辑模式专属：查看歌单歌曲按钮 -->
        <el-form-item v-if="!isAddMode">
          <el-button
              type="primary"
              @click="openSongManageDialog(baseForm.id, baseForm.title)"
              style="margin-right: 10px;"
          >
            查看歌单歌曲
          </el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="baseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBaseInfo">确认保存</el-button>
      </template>
    </el-dialog>

    <!-- 2. 歌单歌曲管理弹窗（查看/添加/删除歌曲） -->
    <el-dialog v-model="songManageVisible" :title="`${currentPlaylistTitle} - 歌曲管理`" width="1000px" :close-on-click-modal="false">
      <!-- 操作栏：添加歌曲 + 批量删除 -->
      <div style="display: flex; justify-content: space-between; margin-bottom: 15px; align-items: center;">
        <el-button
            type="primary"
            :icon="Plus"
            @click="openAllSongDialog"
        >
          添加歌曲
        </el-button>
        <el-button
            type="text"
            :icon="Delete"
            @click="handleBatchDeleteSongs"
            style="color: #ff4d4f;"
            :disabled="selectedSongIds.length === 0 || songLoading"
        >
          批量删除选中歌曲（{{ selectedSongIds.length }} 首）
        </el-button>
      </div>

      <!-- 歌曲列表 -->
      <el-table
          :data="songList"
          border
          style="width: 100%;"
          :loading="songLoading"
          :row-key="(row) => row.id"
          size="small"
          @selection-change="handleSelectSongs"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="id" label="歌曲ID" width="100" />
        <el-table-column prop="name" label="歌曲名" />
        <el-table-column prop="album" label="专辑" width="220" />
        <el-table-column prop="duration" label="时长" width="120">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button
                type="text"
                :icon="Delete"
                @click="handleDeleteSingleSong(scope.row.id)"
                style="color: #ff4d4f;"
                :disabled="songLoading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态提示 -->
      <div v-if="!songLoading && songList.length === 0" class="empty-songs">
        <div style="text-align: center; padding: 60px; color: #909399;">
          <el-icon style="font-size: 48px; margin-bottom: 15px;">
          </el-icon>
          <p>当前歌单暂无歌曲，点击「添加歌曲」按钮选择歌曲</p>
        </div>
      </div>

      <!-- 歌曲分页 -->
      <div v-if="!songLoading && songTotal > 0" style="margin-top: 15px; text-align: right;">
        <el-pagination
            v-model:current-page="songCurrentPage"
            v-model:page-size="songPageSize"
            :page-sizes="[5, 10, 15, 20]"
            :total="songTotal"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSongSizeChange"
            @current-change="handleSongCurrentChange"
        />
      </div>
    </el-dialog>

    <!-- 3. 全量歌曲选择弹窗（用于添加歌曲到歌单） -->
    <el-dialog
        v-model="allSongDialogVisible"
        title="选择歌曲添加到歌单"
        width="1000px"
        :close-on-click-modal="false"
    >
      <!-- 搜索栏 -->
      <div class="all-song-search" style="margin-bottom: 16px; display: flex; gap: 12px; align-items: center;">
        <el-input
            v-model="allSongSearchKeyword"
            placeholder="输入歌曲名/歌手名/专辑名搜索"
            :suffix-icon="Search"
            @keyup.enter.prevent="fetchAllSongList"
            style="flex: 1;"
        />
        <el-button type="primary" @click="fetchAllSongList">
          <el-icon :icon="Search" /> 搜索
        </el-button>
        <el-button @click="resetAllSongSearch">
          <el-icon :icon="Refresh" /> 重置
        </el-button>
      </div>

      <!-- 歌曲列表 -->
      <el-table
          :data="allSongList"
          border
          style="width: 100%;"
          :loading="allSongLoading"
          @selection-change="handleSelectAllSongs"
          :row-key="(row) => row.songId"
          size="small"
          ref="allSongTableRef"
      >
        <el-table-column
            type="selection"
            width="55"
            :selectable="isSongSelectable"
        />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="songId" label="歌曲ID" width="100" />
        <el-table-column prop="songName" label="歌曲名" />
        <el-table-column prop="artistName" label="歌手" width="180" />
        <el-table-column prop="album" label="专辑" width="220" />
        <el-table-column prop="duration" label="时长" width="120">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="all-song-pagination" style="margin-top: 16px; text-align: right;">
        <el-pagination
            v-model:current-page="allSongCurrentPage"
            v-model:page-size="allSongPageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="allSongTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleAllSongSizeChange"
            @current-change="handleAllSongPageChange"
        />
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="allSongDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmAddAllSongs"
            :disabled="selectedAllSongIds.length === 0 || allSongLoading"
        >
          确认添加（已选 {{ selectedAllSongIds.length }} 首）
        </el-button>
      </template>
    </el-dialog>

    <!-- 4. 修改封面弹窗 -->
    <el-dialog
        v-model="coverDialogVisible"
        title="修改歌单封面"
        width="500px"
        :close-on-click-modal="false"
    >
      <div class="cover-upload-container" style="text-align: center; padding: 20px 0;">
        <div style="margin-bottom: 20px;">
          <el-image
              :src="currentCoverUrl || '/static/default-avatar.png'"
              style="width: 200px; height: 200px; object-fit: cover; margin: 0 auto;"
          />
        </div>

        <el-upload
            action="#"
            :on-success="handleCoverUpdateSuccess"
            :file-list="tempCoverFileList"
            accept="image/*"
            :auto-upload="false"
            :on-change="handleTempCoverChange"
        >
          <el-button type="primary" :icon="Upload">选择新封面</el-button>
        </el-upload>

        <p style="margin-top: 15px; color: #909399;">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
      </div>

      <template #footer>
        <el-button @click="coverDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="updatePlaylistCover"
            :disabled="tempCoverFileList.length === 0"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from "element-plus"
import { Plus, Edit, Delete, Search, Upload, Refresh } from '@element-plus/icons-vue'
import http from "@/request/http.js" // 请确保你的请求封装路径正确

// 1. 基础状态定义
const searchForm = reactive({
  title: '',
  style: ''
})

// 歌单列表相关
const playlistList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedPlaylistIds = ref([]) // 存储选中的歌单ID，用于批量删除

// 2. 基础信息弹窗相关（名称/风格/简介）
const baseDialogVisible = ref(false)
const isAddMode = ref(true)  // 控制新增/编辑模式
const baseDialogTitle = ref("新增歌单")
const baseFormRef = ref(null)
const baseForm = ref({
  id: '',
  title: '',
  style: '',
  intro: '',
  cover: ''
})

// 表单验证规则
const baseFormRules = reactive({
  title: [
    { required: true, message: "请输入歌单名称", trigger: "blur" },
    { min: 1, max: 50, message: "歌单名称长度在1-50个字符", trigger: "blur" }
  ],
  style: [
    { required: true, message: "请选择歌单风格", trigger: "change" }
  ],
  intro: [
    { max: 500, message: "简介不能超过500个字符", trigger: "blur" }
  ]
})

// 3. 歌曲管理弹窗相关（支持后端分页）
const songManageVisible = ref(false)
const currentPlaylistId = ref(null)
const currentPlaylistTitle = ref('')
const songList = ref([])          // 后端返回的当前页歌曲列表（使用id）
const songTotal = ref(0)          // 歌曲总条数（后端返回）
const songLoading = ref(false)    // 歌曲加载状态
const songCurrentPage = ref(1)    // 当前页码
const songPageSize = ref(5)       // 每页条数

// 4. 全量歌曲选择弹窗相关
const allSongDialogVisible = ref(false)
const allSongSearchKeyword = ref('')
const allSongList = ref([])       // 全量歌曲列表（使用songId）
const allSongLoading = ref(false)
const allSongCurrentPage = ref(1)
const allSongPageSize = ref(10)
const allSongTotal = ref(0)
const selectedAllSongIds = ref([]) // 存储选中的songId
const existingSongIds = ref(new Set())  // 存储当前歌单已有的歌曲id（来自歌单歌曲的id）
const selectedSongIds = ref([])         // 选中的歌曲id（来自歌单歌曲的id）
const allSongTableRef = ref(null)       // 全量歌曲表格引用

// 5. 封面修改弹窗相关
const coverDialogVisible = ref(false)
const currentCoverId = ref(null)
const currentCoverUrl = ref('')
const tempCoverFileList = ref([])
const tempCoverFile = ref(null)

// 初始化
onMounted(() => {
  fetchPlaylists()
})

// 监听全量歌曲选择变化，同步选中状态
watch(
    () => allSongList.value,
    async (newList) => {
      // 恢复之前选中的歌曲状态（使用songId）
      if (allSongTableRef.value && selectedAllSongIds.value.length > 0) {
        await nextTick() // 等待DOM更新完成
        newList.forEach(row => {
          if (selectedAllSongIds.value.includes(row.songId)) {
            allSongTableRef.value.toggleRowSelection(row, true)
          }
        })
      }
    }
)

// 6. 分页相关方法
// 歌单分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchPlaylists()
}

// 歌单页码变化
const handleCurrentPageChange = (page) => {
  currentPage.value = page
  fetchPlaylists()
}

// 歌曲分页大小变化
const handleSongSizeChange = (size) => {
  songPageSize.value = size
  fetchPlaylistSongs() // 重新请求后端分页数据
}

// 歌曲页码变化
const handleSongCurrentChange = (page) => {
  songCurrentPage.value = page
  fetchPlaylistSongs() // 重新请求后端分页数据
}

// 7. 歌单列表相关方法
// 获取歌单列表
const fetchPlaylists = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchForm.title || '',
      style: searchForm.style || ''
    }

    const response = await http.post('/admin/getAllPlaylists', params)
    const { items = [], total: totalCount = 0 } = response.data || {}

    // 确保正确映射歌单名称字段
    playlistList.value = items.map(item => ({
      id: item.playlistId || item.id,
      title: item.title || item.playlistName || '未知歌单', // 确保有默认值
      cover: item.coverUrl || item.cover,
      style: item.style || '未知风格',
      intro: item.introduction || item.intro || '无简介'
    }))

    total.value = totalCount
  } catch (error) {
    ElMessage.error('获取歌单列表失败：' + (error.response?.data?.msg || error.message))
    playlistList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索和筛选
const handleSearch = () => {
  currentPage.value = 1
  fetchPlaylists()
}

// 重置搜索表单
const resetSearch = () => {
  searchForm.title = ''
  searchForm.style = ''
  currentPage.value = 1
  fetchPlaylists()
}

// 批量选择相关
const handleSelectAll = (selection) => {
  selectedPlaylistIds.value = selection.map(item => item.id)
}

const handleSelectChange = (selection) => {
  selectedPlaylistIds.value = selection.map(item => item.id)
}

// 8. 新增/编辑歌单基础信息相关方法
// 打开新增弹窗
const openAddDialog = () => {
  isAddMode.value = true
  baseDialogTitle.value = '新增歌单'
  baseForm.value = {
    id: '',
    title: '',
    style: '',
    introduction: '',
    cover: ''
  }
  baseDialogVisible.value = true
  if (baseFormRef.value) {
    baseFormRef.value.resetFields()
  }
}

// 打开编辑基础信息弹窗
const openEditBaseDialog = async (id) => {
  try {
    loading.value = true
    const response = await http.get(`/playlist/getPlaylistDetail/${id}`)
    const detail = response.data || {}

    isAddMode.value = false
    baseForm.value = {
      id: detail.playlistId || id,
      title: detail.title || detail.playlistName || '', // 确保获取正确的名称字段
      style: detail.style || '',
      intro: detail.introduction || detail.intro || '',
      cover: detail.coverUrl || detail.cover || ''
    }

    baseDialogTitle.value = '编辑歌单'
    baseDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载歌单详情失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 保存基础信息
const saveBaseInfo = async () => {
  try {
    if (!baseFormRef.value) return
    await baseFormRef.value.validate()

    if (isAddMode.value) {
      // 新增歌单
      await http.post('/admin/addPlaylist', baseForm.value)
      ElMessage.success('新增歌单成功')
    } else {
      // 编辑歌单
      if (!baseForm.value.id) {
        ElMessage.error('编辑失败：歌单ID不存在')
        return
      }
      await http.put('/admin/updatePlaylist', baseForm.value)
      ElMessage.success('编辑歌单成功')
    }

    baseDialogVisible.value = false
    fetchPlaylists()
  } catch (error) {
    if (error.name !== 'Error') return // 忽略表单验证错误
    ElMessage.error('保存失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 单个删除歌单
const deletePlaylist = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这个歌单吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await http.delete(`/admin/deletePlaylist/${id}`)
    ElMessage.success('删除成功')
    fetchPlaylists()
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

// 批量删除歌单（新增功能）
const handleBatchDeletePlaylists = async () => {
  if (selectedPlaylistIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的歌单')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedPlaylistIds.value.length} 个歌单吗？此操作不可撤销！`,
        '批量删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'danger'
        }
    )

    loading.value = true
    // 调用批量删除接口，传递歌单ID列表
    await http.delete('/admin/deletePlaylists', {
      data: selectedPlaylistIds.value // 传递ID数组作为请求体
    })

    ElMessage.success(`成功删除 ${selectedPlaylistIds.value.length} 个歌单`)
    selectedPlaylistIds.value = [] // 清空选中状态
    fetchPlaylists() // 刷新歌单列表
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.response?.data?.msg || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 9. 歌曲管理相关方法（支持后端分页）
// 打开歌曲管理弹窗
const openSongManageDialog = async (playlistId, playlistTitle) => {
  try {
    currentPlaylistId.value = playlistId
    currentPlaylistTitle.value = playlistTitle || '未知歌单'

    // 初始化分页参数
    songCurrentPage.value = 1
    songPageSize.value = 5

    // 获取歌单歌曲列表（带分页参数）
    await fetchPlaylistSongs()

    // 关闭基础信息弹窗，打开歌曲管理弹窗
    baseDialogVisible.value = false
    songManageVisible.value = true
  } catch (error) {
    ElMessage.error('加载歌单歌曲失败：' + (error.response?.data?.msg || error.message))
  }
}

// 获取当前歌单的歌曲列表（后端分页查询，使用id）
const fetchPlaylistSongs = async () => {
  if (!currentPlaylistId.value) return

  songLoading.value = true
  try {
    // 构造请求参数：包含 pageNum、pageSize、id
    const params = {
      pageNum: songCurrentPage.value,
      pageSize: songPageSize.value,
      id: currentPlaylistId.value
    }

    // 调用后端分页接口
    const response = await http.post('/playlist-binding/getSongsByPlaylistId', params)
    const { data = {} } = response
    const { items = [], total = 0 } = data || {}

    // 确保歌曲名称正确映射（使用id）
    songList.value = items.map(song => ({
      ...song,
      name: song.name || song.songName || '未知歌曲名' // 确保有默认值
    }))

    songTotal.value = total // 后端返回的总条数
  } catch (error) {
    ElMessage.error('获取歌曲列表失败：' + (error.response?.data?.msg || error.message))
    songList.value = []
    songTotal.value = 0
  } finally {
    songLoading.value = false
  }
}

// 打开全量歌曲选择弹窗
const openAllSongDialog = () => {
  if (!currentPlaylistId.value) return

  allSongSearchKeyword.value = ''
  allSongCurrentPage.value = 1
  allSongList.value = []
  selectedAllSongIds.value = []

  // 收集当前歌单已有的歌曲 ID（使用id字段），避免重复添加
  existingSongIds.value = new Set(
      songList.value.map((song) => song.id)
  )

  allSongDialogVisible.value = true
  fetchAllSongList()
}

// 获取全量歌曲列表（使用songId）
const fetchAllSongList = async () => {
  allSongLoading.value = true
  try {
    const params = {
      pageNum: allSongCurrentPage.value,
      pageSize: allSongPageSize.value,
      songName: allSongSearchKeyword.value || ''
    }

    const response = await http.post('/song/getAllSongs', params)
    const { items = [], total: totalCount = 0 } = response.data || {}

    allSongList.value = items
    allSongTotal.value = totalCount
  } catch (error) {
    ElMessage.error('获取歌曲列表失败：' + (error.response?.data?.msg || error.message))
    allSongList.value = []
    allSongTotal.value = 0
  } finally {
    allSongLoading.value = false
  }
}

// 重置歌曲搜索
const resetAllSongSearch = () => {
  allSongSearchKeyword.value = ''
  allSongCurrentPage.value = 1
  selectedAllSongIds.value = []
  fetchAllSongList()
}

// 歌曲分页处理
const handleAllSongSizeChange = (size) => {
  // 保存当前选中状态（使用songId）
  const currentSelected = [...selectedAllSongIds.value]

  allSongPageSize.value = size
  allSongCurrentPage.value = 1

  // 重新加载后恢复选中状态
  fetchAllSongList().then(() => {
    selectedAllSongIds.value = currentSelected
  })
}

const handleAllSongPageChange = (page) => {
  // 保存当前选中状态（使用songId）
  const currentSelected = [...selectedAllSongIds.value]

  allSongCurrentPage.value = page

  // 重新加载后恢复选中状态
  fetchAllSongList().then(() => {
    selectedAllSongIds.value = currentSelected
  })
}

// 处理歌曲选择（使用songId）
const handleSelectAllSongs = (selection) => {
  // 过滤掉已在歌单中的歌曲（全量歌曲用songId，歌单歌曲用id）
  const validSelection = selection.filter(song =>
      !existingSongIds.value.has(song.songId)
  )

  selectedAllSongIds.value = validSelection.map(song => song.songId)
}

// 判断歌曲是否可选中（不在当前歌单中，全量歌曲用songId，歌单歌曲用id）
const isSongSelectable = (row) => {
  return !existingSongIds.value.has(row.songId)
}

// 确认添加选中歌曲到歌单（使用songId）
const confirmAddAllSongs = async () => {
  if (selectedAllSongIds.value.length === 0 || !currentPlaylistId.value) {
    ElMessage.warning('请先选中要添加的歌曲')
    return
  }

  try {
    const loading = ElLoading.service({
      text: '正在添加歌曲...',
      lock: true
    })

    // 调用添加歌曲接口（传递songId数组）
    await http.post('/playlist-binding/addSongsToPlaylist', {
      playlistId: currentPlaylistId.value,
      songIds: selectedAllSongIds.value  // 传递songId数组
    })

    ElMessage.success(`成功添加 ${selectedAllSongIds.value.length} 首歌曲`)

    // 刷新歌单歌曲列表（保持当前分页状态）
    await fetchPlaylistSongs()

    // 关闭弹窗并重置选择状态
    selectedAllSongIds.value = []
    allSongDialogVisible.value = false
  } catch (error) {
    ElMessage.error('添加歌曲失败：' + (error.response?.data?.msg || error.message))
  } finally {
    ElLoading.service().close()
  }
}

// 处理已选歌曲的选择（使用id）
const handleSelectSongs = (selection) => {
  selectedSongIds.value = selection.map(song => song.id)
}

// 批量删除已选歌曲（使用id）
const handleBatchDeleteSongs = async () => {
  if (selectedSongIds.value.length === 0 || !currentPlaylistId.value) {
    ElMessage.warning('请先选中要删除的歌曲')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedSongIds.value.length} 首歌曲吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    songLoading.value = true
    // 调用批量删除接口（传递id数组）
    await http.post('/playlist-binding/removeSongsFromPlaylist', {
      playlistId: currentPlaylistId.value,
      songIds: selectedSongIds.value  // 传递id数组
    })

    ElMessage.success(`成功删除 ${selectedSongIds.value.length} 首歌曲`)

    // 刷新歌单歌曲列表（保持当前分页状态）
    await fetchPlaylistSongs()
    selectedSongIds.value = []
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message))
    }
  } finally {
    songLoading.value = false
  }
}

// 单个删除歌曲（使用id）
const handleDeleteSingleSong = async (songId) => {
  if (!currentPlaylistId.value) return

  try {
    await ElMessageBox.confirm(
        '确定要删除这首歌曲吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    songLoading.value = true
    // 调用删除接口（传递id）
    await http.post('/playlist-binding/removeSongsFromPlaylist', {
      playlistId: currentPlaylistId.value,
      songIds: [songId]  // 传递id
    })

    ElMessage.success('歌曲删除成功')

    // 刷新歌单歌曲列表（保持当前分页状态）
    await fetchPlaylistSongs()
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message))
    }
  } finally {
    songLoading.value = false
  }
}

// 格式化时长（秒 -> mm:ss）
const formatDuration = (seconds) => {
  if (!seconds) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 10. 封面修改相关方法
// 打开封面修改弹窗
const openCoverDialog = (id, coverUrl) => {
  currentCoverId.value = id
  currentCoverUrl.value = coverUrl
  tempCoverFileList.value = []
  tempCoverFile.value = null
  coverDialogVisible.value = true
}

// 封面上传前校验
const beforeCoverUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('上传封面图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传封面图片大小不能超过 2MB!')
  }

  return isJpgOrPng && isLt2M
}

// 处理临时封面文件选择
const handleTempCoverChange = (uploadFile) => {
  if (!beforeCoverUpload(uploadFile.raw)) {
    tempCoverFileList.value = []
    return
  }
  tempCoverFileList.value = [uploadFile]
  tempCoverFile.value = uploadFile.raw
}

// 更新歌单封面
const updatePlaylistCover = async () => {
  if (!tempCoverFile.value || !currentCoverId.value) return

  const loadingInstance = ElLoading.service({
    text: '正在更新封面...',
    lock: true
  })

  try {
    const formData = new FormData()
    formData.append('cover', tempCoverFile.value)

    const response = await http.patch(
        `/admin/updatePlaylistCover/${currentCoverId.value}`,
        formData,
        {headers: {'Content-Type': 'multipart/form-data'}}
    )

    if (response.code === 0) {
      ElMessage.success('封面更新成功')
      coverDialogVisible.value = false
      fetchPlaylists() // 刷新歌单列表
    } else {
      ElMessage.error('封面更新失败: ' + (response.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('封面更新失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    loadingInstance.close()
  }
}

// 封面更新成功回调
const handleCoverUpdateSuccess = () => {
  ElMessage.success('封面上传成功')
}
</script>

<style scoped>
.playlist-manage {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

/* 搜索区样式 */
.search-section {
  width: 100%;
  padding: 20px;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
}

.search-item {
  display: flex;
  align-items: center;
  margin-bottom: 0 !important;
}

.style-select {
  width: 100%;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.search-btn, .reset-btn {
  margin-right: 10px;
  padding: 8px 20px;
  border-radius: 4px;
}

/* 表格与分页样式 */
.content-section {
  width: 100%;
  box-sizing: border-box;
}

.pagination-container {
  width: 100%;
  text-align: right;
  padding: 10px 0;
}

/* 弹窗内样式 */
.empty-songs {
  border: 1px dashed #e5e7eb;
  border-radius: 6px;
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .playlist-manage {
    padding: 10px;
  }

  .search-section {
    padding: 10px;
  }
}
</style>

